package com.thb.message.dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.thb.message.dao.IMessageDao;
import com.thb.message.model.Message;

@Repository
public class MessageDaoImpl implements IMessageDao {
	
	@Autowired
	private JdbcTemplate jTemplate;

	@Override
	public int addMessage(Message message) {
		
		 String sql = "insert into message( `type`,`content`,`recv_user_id`,`send_user_id`,`time`,`status`) values (?,?,?,?,?,?)";
		 
		 java.sql.Timestamp sdate = new java.sql.Timestamp(message.getTime().getTime());
		
		Object[] args = new Object[] { message.getType(),message.getContent(),message.getRecvUserId(),message.getSendUserId(),sdate,message.getStatus() };
		int[] types = new int[]{Types.INTEGER,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.TIMESTAMP,Types.INTEGER};
		
		int id =  jTemplate.update(sql, args,types);
		return id;
	}
	
	

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List<Message> findByUser(String recvUserId) {
		String sql = "select * from message where recv_user_id = ?  order by time desc";
		Object[] arg = new Object[] { recvUserId };
		
		return jTemplate.query(sql, arg,new RowMapper() {
			public Object mapRow(ResultSet rs, int no) throws SQLException {

				return beanMapper(rs, no);
			}
		});
	}
	
	private Message beanMapper(ResultSet rs, int no) throws SQLException {

		Message vo = new Message();
		vo.setMessageId(rs.getInt("message_id"));
		vo.setContent(rs.getString("content"));
		vo.setRecvUserId(rs.getString("recv_user_id"));
		vo.setTime(rs.getTimestamp("time"));
		vo.setSendUserId(rs.getString("send_user_id"));
		vo.setStatus(rs.getInt("status"));
		vo.setType(rs.getInt("type"));
		return vo;
	}

}
